package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.utils.Error;
import com.tomkk.utils.MysqlOperation;
import com.tomkk.utils.Success;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * Created by Tomkk on 2016/5/22.
 */
@WebServlet(name = "RegisterServlet",urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String realname = request.getParameter("realname");
        String mobile = request.getParameter("mobile");
        String email = request.getParameter("email");


        String sql = "INSERT INTO user (username,password,nickname,realname,mobile,email) VALUE('"+username+"', '"+password+"', '"+nickname+"', '"+realname+"', '"+mobile+"', '"+email+"')";
        Gson gson =  new Gson();
        MysqlOperation operation = new MysqlOperation();
        operation.checkConn();
        int resNum = operation.insert(sql);
        try {
            if(resNum == 0){
                Error res = new Error(2,"服务器错误");
                String json = gson.toJson(res);
                PrintWriter writer = response.getWriter();
                writer.print(json);
                writer.flush();
            }
            else{
                Success res = new Success(0,"注册成功");
                String json = gson.toJson(res);
                PrintWriter writer = response.getWriter();
                writer.print(json);
                writer.flush();
            }
            operation.closeDB();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
